package com.libreaccess.reporting.utils;

import com.libreaccess.reporting.beans.ReportsDAO;
import com.libredigital.reporting.schema.ReportResource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.util.FileResolver;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.naming.NamingException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;

@Service(value = "customFileResolver")
public class CustomFileResolver implements FileResolver {
	@Resource
	private static ReportsDAO rDao;

	public void setrDao(ReportsDAO rDao) {
		CustomFileResolver.rDao = rDao;
	}

	final Logger logger = new Logger(getClass());
	private Long logId = 0L;

	public CustomFileResolver() {
	}

	public CustomFileResolver(Long logId) {
		this.logId = logId;
	}

	/**
	 *
	 */
	public File resolveFile(String fileName) {
		File file = null;
		logger.debug("Requested fileName:'"+fileName+"'");
		
		if (fileName != null) {
			ReportResource r;
//			String name = fileName.substring(fileName.lastIndexOf('\\') + 1);
//			String nameOnly = name.substring(0,name.lastIndexOf('.'));
			String extOnly = fileName.substring(fileName.lastIndexOf('.')+1);
			
			//Utils.ResourceType path = Utils.ResourceType.valueOf(fileName.substring(0, fileName.indexOf('\\')));
			try {
				if (extOnly.equals("jasper"))
				{
					fileName = fileName.substring(0, fileName.lastIndexOf('.'))+".jrxml";
				}
				
				r = rDao.getResourceByFullName(fileName);
				
				if (r != null) {
					if (logId != 0) //logId = 0 for SOAP services
					{
						rDao.setLogDetail(logId, r.getId());
					}
					file = File.createTempFile(r.getType() + " " + SimpleUtils.formatCurrentDate(), extOnly.equals("jasper")? "jrxml":extOnly);
					file.deleteOnExit();
					FileOutputStream fileOuputStream = new FileOutputStream(file);
					if (extOnly.equals("jasper"))
					{
						JasperCompileManager.compileReportToStream(JasperUtils.loadReport(r.getSubreportContent().getBytes("UTF-8")), (OutputStream)fileOuputStream);
					}
					else
					{
						fileOuputStream.write(r.getResourceContent());	
					}

					fileOuputStream.close();
					
					return file;
				}
				else
				{
					logger.error("Requested fileName isn't exist:'"+fileName+"'");			
				}
			} catch (NullPointerException ex) {
				logger.error(ex.getMessage());
			} catch (NamingException ex) {
				logger.error(ex.getMessage());
			} catch (SQLException ex) {
				logger.error(ex.getMessage());
			} catch (IOException ex) {
				logger.error(ex.getMessage());
			} catch (JRException ex) {
				logger.error(ex.getMessage());
			}
		}

		return file;
	}

}
